import React, { useEffect, useMemo } from 'react';

import { ExclamationCircleOutlined } from '@ant-design/icons';

import type { HomeStatistics, MessageStatistics } from '@/api/homeApi';
import { useECharts } from '@/hooks/useEcharts';

import TimeRangeSelector from '../components/TimeRangeSelector';

/**
 * 合并后的消息数据接口
 */
interface MergedMessageItem {
  /** 日期字符串 */
  dateString?: string;
  /** MQTT消息数量 */
  mqttMsg?: number;
  /** API调用数量 */
  apiCall?: number;
}

/**
 * 合并MQTT消息统计和API调用统计数据
 * 将两个按日期统计的数组合并为一个包含两种数据的数组
 * @param mqttArray MQTT消息统计数组
 * @param apiArray API调用统计数组
 * @returns 合并后的数据数组
 */
function mergeMsgCountArrays(
  mqttArray: MessageStatistics[],
  apiArray: MessageStatistics[]
): MergedMessageItem[] {
  // 使用Map存储每个日期的数据，避免重复
  const dateMap = new Map<string, MergedMessageItem>();

  // 处理MQTT消息数据
  mqttArray.forEach(item => {
    const date = item.dateString || '';
    if (!dateMap.has(date)) {
      dateMap.set(date, {
        dateString: date,
        mqttMsg: 0,
        apiCall: 0,
      });
    }
    const current = dateMap.get(date);
    if (current) {
      current.mqttMsg = item.msgCount || 0;
    }
  });

  // 处理API调用数据
  apiArray.forEach(item => {
    const date = item.dateString || '';
    if (!dateMap.has(date)) {
      dateMap.set(date, {
        dateString: date,
        mqttMsg: 0,
        apiCall: 0,
      });
    }
    const current = dateMap.get(date);
    if (current) {
      current.apiCall = item.msgCount || 0;
    }
  });

  // 转换为数组并按日期排序
  return Array.from(dateMap.values()).sort((a, b) => {
    if (a.dateString && b.dateString) {
      return a.dateString.localeCompare(b.dateString);
    }
    return 0;
  });
}

/**
 * 消息量统计视图组件
 * 展示MQTT消息数和API调用数的时间趋势图表
 */
const MessageView: React.FC<{
  data: HomeStatistics;
  onChange?: (value: number) => void;
}> = ({ data, onChange }) => {
  const { domRef, setOptions } = useECharts();

  /**
   * 合并后的消息统计数据
   * 将MQTT消息统计和API调用统计按日期合并
   */
  const messageData: MergedMessageItem[] = useMemo(() => {
    if (!data?.mqttMsgStatisticsList || !data?.apiCallStatisticsList) {
      return [];
    }
    return mergeMsgCountArrays(data.mqttMsgStatisticsList, data.apiCallStatisticsList);
  }, [data.mqttMsgStatisticsList, data.apiCallStatisticsList]);

  // 配置图表
  useEffect(() => {
    const dates = messageData.map(item => item.dateString || '');
    const mqttMsgData = messageData.map(item => item.mqttMsg || 0);
    const apiCallData = messageData.map(item => item.apiCall || 0);

    setOptions({
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross',
          crossStyle: {
            color: '#999',
          },
        },
        formatter: function (params: any) {
          let result = `${params[0].axisValue}<br/>`;
          params.forEach((param: any) => {
            result += `${param.marker}${param.seriesName}: ${param.value.toLocaleString()}<br/>`;
          });
          return result;
        },
      },
      legend: {
        // data: ['汇总传输数据量', '汇总传输消息量'],
        bottom: 10,
        left: 'center',
        itemWidth: 25,
        itemHeight: 14,
        itemGap: 30,
        textStyle: {
          color: '#5A6170',
          fontSize: 12,
        },
        // formatter: function (name: string) {
        //   if (name === '汇总传输数据量') {
        //     return name + ' 1436251';
        //   } else if (name === '汇总传输消息量') {
        //     return name + ' 967922';
        //   }
        //   return name;
        // },
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '20%',
        top: '10%',
        containLabel: true,
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: dates,
        axisLine: {
          lineStyle: {
            color: '#E5E6EB',
          },
        },
        axisTick: {
          show: false,
        },
        axisLabel: {
          color: '#86909C',
          fontSize: 12,
        },
        splitLine: {
          show: false,
          lineStyle: {
            color: '#F2F3F5',
            type: 'solid',
          },
        },
      },
      yAxis: {
        type: 'value',
        axisLine: {
          show: false,
        },
        axisTick: {
          show: false,
        },
        axisLabel: {
          color: '#86909C',
          fontSize: 12,
          formatter: function (value: number) {
            if (value >= 100000) {
              return (value / 10000).toFixed(0) + '万';
            }
            return value.toString();
          },
        },
        splitLine: {
          lineStyle: {
            color: '#F2F3F5',
            type: 'solid',
          },
        },
      },
      series: [
        {
          name: '消息数',
          type: 'line',
          smooth: true,
          symbol: 'none',
          lineStyle: {
            color: '#00D4AA',
            width: 2,
          },
          data: mqttMsgData,
          // markLine: {
          //   data: [
          //     {
          //       xAxis: '5',
          //       lineStyle: {
          //         color: '#3370FF',
          //         type: 'dashed',
          //         width: 1,
          //       },
          //     },
          //     {
          //       xAxis: '9',
          //       lineStyle: {
          //         color: '#3370FF',
          //         type: 'dashed',
          //         width: 1,
          //       },
          //     },
          //   ],
          //   symbol: 'none',
          //   silent: true,
          // },
        },
        {
          name: 'API调用数',
          type: 'line',
          smooth: true,
          symbol: 'none',
          lineStyle: {
            color: '#3370FF',
            width: 2,
          },
          data: apiCallData,
        },
      ],
    });
  }, [setOptions, messageData]);

  return (
    <div className="grid grid-cols-1 gap-6 my-4">
      <div className="public-card p-6">
        <div className="mb-2 flex align-center justify-between">
          <div className="text-lg font-semibold text-gray-800 mb-2">
            消息量统计
            <ExclamationCircleOutlined className="text-gray-500 text-sm ml-2" />
          </div>
          <TimeRangeSelector onChange={onChange} />
        </div>

        <div ref={domRef} className="w-full h-80" style={{ minHeight: '320px' }} />
      </div>
    </div>
  );
};

export default MessageView;
